﻿using CommonUtils;
using EnvDTE;
using Microsoft.VisualStudio.Shell;
using System;
using System.Linq;
using System.Text;

namespace CodeAssistant.Commands.Wpf
{
    internal class SortGridElements
    {
        public static void Handler(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var dte = Package.GetGlobalService(typeof(DTE)) as DTE;
            var document = dte.ActiveDocument;

            if (document == null || FileUtil.GetExtension(document.FullName) != ".xaml")
            {
                EditorUtil.ShowMessage("Please Open and Select a Xaml File");
                return;
            }

            var xaml = FileUtil.GetText(document.FullName);
            var gridXml = xaml.GetBetween("<Grid>", "</Grid>", false);
            var elements = GridElement.GetElements(gridXml);
            elements = elements.OrderBy(m => m.MarginLeft).OrderBy(m => m.MarginTop).ToArray();
            var newGridXaml = new StringBuilder();
            elements.Foreach(m => newGridXaml.AppendLine(m.Xml));
            xaml = xaml.Replace(gridXml, newGridXaml.ToString());

            FileUtil.Save(document.FullName, xaml);
            EditorUtil.ShowMessage(document.Name + " has inited !");
        }
    }
}
